/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package File;

import DB.DBConnectionJm;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import java.util.*;
import javax.servlet.ServletContext;


import com.google.code.javascribd.connection.ScribdClient;
import com.google.code.javascribd.connection.ScribdConnectionException;
import com.google.code.javascribd.connection.StreamableData;
import com.google.code.javascribd.docs.Upload;
import com.google.code.javascribd.docs.UploadResponse;
import com.google.code.javascribd.type.Access;
import com.google.code.javascribd.type.ApiKey;
import com.google.code.javascribd.type.FileData;

/**
 *
 * @author Tiong Jia Ming
 */
public class FileUpload extends HttpServlet {

    private ScribdClient client = new ScribdClient();
    private UploadResponse responseScribd = null;
    private ApiKey apiKey = new ApiKey("36u5bcyvy0kxjqi4zc671");
    private DBConnectionJm dbc = null;
    private File file = null;
    private String fileName = "";
    private Scribd scribd = null;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        scribd = new Scribd();
        try {
            int maxFileSize = request.getContentLength();
            int maxMemSize = request.getContentLength();
            ServletContext context = this.getServletContext();
            String filePath = context.getInitParameter("location");
            String contentType = request.getContentType();
            if ((contentType.indexOf("multipart/form-data") >= 0)) {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //this is a temp space to hold the file
                factory.setSizeThreshold(maxMemSize);
                factory.setRepository(new File("c:\\temp"));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                //maxFileSize is the size of the file that is currently been uploaded
                upload.setSizeMax(maxFileSize);
                try {
                    List fileItems = upload.parseRequest(request);
                    Iterator i = fileItems.iterator();
                    out.println("<html>"
                            + "<head><title>Successful Upload</title></head>"
                            + "<body>");
                    fileName = "";
                    //initalize a new connection
                    dbc = new DBConnectionJm();
                    while (i.hasNext()) {
                        FileItem fi = (FileItem) i.next();
                        if (!fi.isFormField()) {
                            // the full absolute path name
                            fileName = fi.getName();
                            if (fileName.isEmpty()) {
                                request.setAttribute("error", "No File Selected!");
                                response.sendRedirect(request.getContextPath() + "/File/Upload.jsp");
                            } else {
                                dbc.setQuery("Select * from FileRecords where FileName = ?");
                                dbc.setAttributes(new String[]{fileName});
                                ResultSet rs = dbc.doQuery();
                                // the lastIndexOf is to get the name of the file
                                file = new File(context.getRealPath("/") + filePath + fileName);
                                if (file.exists()) {
                                    file = new File(context.getRealPath("/") + filePath + dbc.getSize() + fileName);
                                }
                                fi.write(file);
                                if (file.exists()) {
                                    System.out.println("yes");
                                }
                                scribd.ScribdUpload(file, fileName);
                                out.println("Uploaded Filename: " + context.getRealPath("/") + filePath + fileName + "<br>");
                                out.println(fileName);
                                dbc.doClose();
                                InsertDB(maxFileSize, filePath);
                            }
                        }
                    }
                    out.println("</body></html>");

                } catch (Exception ex) {
                    System.out.println(ex);
                    out.println(ex);
                }
            } else {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Unsuccessful Upload</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<p>No file uploaded</p>");
                out.println("</body>");
                out.println("</html>");
            }
        } finally {
            out.close();
        }

    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,
            IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException,
            IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    public void InsertDB(int maxFileSize, String filePath) {
        //check how many files are there in total
        dbc = new DBConnectionJm();
        dbc.setQuery("Select * from FileRecords");
        dbc.doQuery();
        //the number of the files in the DB will be the id of the new file in the DB
        int size = dbc.getSize();
        dbc.setUpdate("Insert into FileRecords values(" + size + ",?,?,?,'Math',NOW(),0,?,?,?)");
        dbc.setAttributes(new String[]{fileName, Integer.toString(maxFileSize), filePath, file.getAbsolutePath(), scribd.getDocID(), scribd.getKey()});
        dbc.doUpdate();
        dbc.doClose();

    }
}
